package com.lianziyou.chain.common.utils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import org.web3j.abi.datatypes.Address;

/**
 * 转换合约的数据类型
 */
public class ConvertContractValue {

    /**
     * 转换一个数值为地址
     *
     * @param value
     * @return
     */
    public static String convertToAddress(String value) {
        Assert.isTrue(!StringUtils.isEmpty(value), "value不能为空");
        if (value.length() == 66) {
            return new Address(value).toString();
        } else if (value.length() == 64) {
            return new Address("0x" + value).toString();
        }
        return "0x" + value.substring(26);
    }


    /**
     * 转换一个数据集为数据列表
     *
     * @param value
     * @return
     */
    public static List<String> convertDataToValueList(String value) {
        Assert.isTrue(!StringUtils.isEmpty(value), "value不能为空");
        Assert.isTrue(value.length() >= 66 && (value.length() - 2) % 64 == 0, "value格式错误");
        ArrayList<String> list = new ArrayList<>();
        String valueNew = value.substring(2);
        int length = valueNew.length();
        for (int i = 0; i <= length - 64; i += 64) {
            list.add("0x" + valueNew.substring(i, i + 64));
        }
        return list;
    }

    public static BigDecimal bigIntegerToBigDecimal(BigInteger value, int decimals) {
        return new BigDecimal(value).divide(BigDecimal.TEN.pow(decimals), new MathContext(decimals));
    }


}
